package com.yin.servlet;

import com.yin.annotation.*;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class YinDispatcherServlet  extends HttpServlet {
    private Properties contextConfig = new Properties();
    private List<String> classNames = new ArrayList<>();
    private Map<String,Object> ioc = new ConcurrentHashMap<>();
    private Map<String,Method> handlerMapping = new HashMap<>();

    @Override
    public void init(ServletConfig config) throws ServletException {
        //定位
        doLoadConfig(config.getInitParameter("contextConfigLocation"));
        //加载
        doScanner(contextConfig.getProperty("scanPackage"));
        //注册
        doRegisty();
        doAutowired();
        initHandlerMapping();
        System.err.println("Yin Spring framework is init");
    }

    private void doLoadConfig(String contextConfigLocation){
        InputStream fis = this.getClass().getClassLoader()
                .getResourceAsStream(contextConfigLocation.replace("classpath:",""));
        try {
            contextConfig.load(fis);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(null != fis){
                try {
                    fis.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }

    private void doScanner(String scanPackage){
        URL url = this.getClass().getClassLoader()
                .getResource("/" + scanPackage.replaceAll("\\.","/"));
        File classpath = new File(url.getFile());
        for (File file : classpath.listFiles()){
            if(file.isDirectory()){
                doScanner(scanPackage + "." + file.getName());
            }else {
                if(!file.getName().endsWith(".class")) continue;
                String className = scanPackage + "." + file.getName().replace(".class","");
                classNames.add(className);
            }
        }
    }

    private void doRegisty(){
        if(classNames.isEmpty()) return;
        try {
            for (String className : classNames){
                Class clazz = Class.forName(className);
                String beanName = null;
                // ioc 中放的是BeanDefinition
                if(clazz.isAnnotationPresent(YinService.class)){
                    YinService service = (YinService) clazz.getAnnotation(YinService.class);
                     beanName = service.value();
                    if(beanName == null || "".equals(beanName.trim())){
                        beanName = toLowerFirstCase(clazz.getSimpleName());
                    }
                    Object instance = clazz.newInstance();
                    ioc.put(beanName,instance);

                        for (Class i : clazz.getInterfaces()){
                            if(ioc.containsKey(i.getName())){
                                throw new Exception("the " + i.getName() + "is exists!");
                            }
                            ioc.put(i.getName(),instance);
                        }


                }else if (clazz.isAnnotationPresent(YinController.class)){
                   beanName = toLowerFirstCase(clazz.getSimpleName());
                   ioc.put(beanName,clazz.newInstance());
                }else {
                    continue;
                }

            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private  String toLowerFirstCase(String name){
        if (name == null || name.length() == 0) return null;
        char[] names = name.toCharArray();
        names[0] += 32;
        return String.valueOf(names);
    }

    private void doAutowired(){
        if(ioc.isEmpty()) return;
        for(Map.Entry<String,Object> entry : ioc.entrySet()){
            Field[] fields = entry.getValue().getClass().getDeclaredFields();
            for(Field field : fields){
                if(field.isAnnotationPresent(YinAutowired.class)){
                    YinAutowired autowired = field.getAnnotation(YinAutowired.class);
                    String beanName = autowired.value().trim();
                    if("".equals(beanName.trim())){
                        beanName = field.getType().getName();
                    }
                    field.setAccessible(true);
                    try {
                        field.set(entry.getValue(),ioc.get(beanName));
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    private void initHandlerMapping()

    {
        if (ioc.isEmpty()) return;
        String baseurl = null;
        for(Map.Entry<String,Object> entry : ioc.entrySet()){
            Class clazz = entry.getValue().getClass();
            if(!clazz.isAnnotationPresent(YinController.class)) continue;
            YinRequestMapping mapping = (YinRequestMapping) clazz.getAnnotation(YinRequestMapping.class);
            baseurl = mapping.value();

            for (Method method : clazz.getMethods()){
                if(!method.isAnnotationPresent(YinRequestMapping.class)) continue;
                YinRequestMapping mapping1 = method.getAnnotation(YinRequestMapping.class);
                String url = ("/" + baseurl + "/" + mapping1.value()).replaceAll("/+","/");
                handlerMapping.put(url,method);
            }
        }


    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            doDispatch(req,resp);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void doDispatch(HttpServletRequest req,HttpServletResponse resp) throws Exception{
        String url = req.getRequestURI();
        String contextPath = req.getContextPath();
        url = url.replaceAll(contextPath,"").replaceAll("/+","/");
        if(!this.handlerMapping.containsKey(url)){
            resp.getWriter().write("404 not found!");
            return;
        }
        Method method = handlerMapping.get(url);
        Map<String,String[]> params = req.getParameterMap();
        Class[] parameterTypes = method.getParameterTypes();
        Map<String,String[]> parameterMap = req.getParameterMap();
        Object[] paramValues = new Object[parameterTypes.length];
        for (int i = 0; i < parameterTypes.length; i++){
            Class parameterType = parameterTypes[i];
            if(parameterType == HttpServletRequest.class){
                paramValues[i] = req;
                continue;
            }else if(parameterType == HttpServletResponse.class){
                paramValues[i] = resp;
                continue;
            }else if(parameterType == String.class){
                Annotation[][] pa = method.getParameterAnnotations();
                for(int j= 0; j < pa.length; j++){
                    for (Annotation a : pa[i]){
                        if(a instanceof YinRequestParam){
                            String paramValue = ((YinRequestParam) a).value();
                            if(!"".equals(paramValue.trim())){
                                String value = Arrays.toString(parameterMap.get(paramValue))
                                        .replaceAll("\\[|\\]","")
                                        .replaceAll("\\s",",");
                                paramValues[i] = value;
                            }
                        }
                    }
                }
            }
        }
        String beanName = toLowerFirstCase(method.getDeclaringClass().getSimpleName());
        method.invoke(ioc.get(beanName),paramValues);
    }

    public static void main(String[] args) {
        System.err.println("com.yin.ok".replaceAll("\\.","/"));
       File file = new File("/Users/yintingting/Documents/apache-tomcat-8.5.35/webapps/ROOT/WEB-INF/classes/com/yin/service");
       System.err.println(file.getName());
    }
}
